from django.http import JsonResponse
from django.shortcuts import render
from .models import Area
from tools.response_code import RETCODE
import logging
logger = logging.getLogger('django')
# Create your views here.
def areas_view(request):
    area_id = request.GET.get('area_id')
    if not area_id:
        # 获取到省的查询集 query set
        province_qs = Area.objects.filter(parent__isnull=True)
        # 改装数据
        province_list = []
        for province in province_qs:
            province_list.append({'id':province.id,'name':province.name})
        # 返回响应
        data = {
            "code": "0",
            "errmsg":"OK",
            'province_list':province_list
        }
        return JsonResponse(data)
    else:
        try:
            # 根据area_id查询area_id对应所有 市或者区的数据
            parent_area = Area.objects.get(id = area_id) # 返回一个具体的地区对象，有可能是一个省，或者是一个市
            sub_model_list = parent_area.subs.all()
            # 拼接数据
            sub_list = []
            for sub in sub_model_list:
                sub_list.append({'id':sub.id,'name':sub.name})

            data = {
                  "code":"0",
                  "errmsg":"OK",
                  "sub_data":{
                      "id":area_id,
                      "name":parent_area.name,
                      "subs":sub_list
                  }
                }
            return JsonResponse(data)
        except Area.DoesNotExist as e:
            logger.error(e)
            return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '城市或区数据错误'})
